<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/7/25 0025
 * Time: 8:35
 */

namespace app\service;
use phpmailer\BaseException;
use think\Db;


/**
 * 供应商服务层
 * @author   juzi
 * @blog    https://blog.csdn.net/juziaixiao
 * @version  0.0.1
 * @datetime 2020年7月25日08:36:08
 */
class SupplierService extends BaseService
{
    /**
     * 供应商列表条件
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version  0.0.1
     * @datetime 2020年7月24日13:22:12
     * @param    [array]          $params [输入参数]
     */
    public static function SupListWhere($params = [])
    {

        $where = [];
            if(!empty($params['keywords']))
            {
                $where[] =['supplier_name|relation_phone', 'like', '%'.$params['keywords'].'%'];
            }


        // 省市区
        if(!empty($params['province']))
        {
            $where[] = ['province', '=', $params['province']];
        }
        if(!empty($params['city']))
        {
            $where[] = ['city', '=', $params['city']];
        }
        if(!empty($params['area']))
        {
            $where[] = ['area', '=', $params['area']];
        }


//        // 状态 审核状态 1 审核中 2 通过（合作中） 3驳回 4.已关闭
     /*   if(isset($params['audit_status']) && $params['audit_status'] > -1)
        {
            $where[] = ['audit_status', '=', intval($params['audit_status'])];
        }*/
        if(!empty($params['audit_status']))
        {
            $where[] = ['audit_status', '=', intval($params['audit_status'])];
        }
        if(!empty($params['from_client']))
        {
            $where[] = ['from_client', '=', intval($params['from_client'])];
        }
        return $where;
    }

    /**
     * 数据处理
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年7月24日13:30:30
     * @desc    description
     * @param   [array]          $data [供应商数据 二维数组]
     */
    public static function DataDealWith($data){

        if(!empty($data) && is_array($data))
        {
            foreach($data as &$v)
            {
                if(is_array($v))
                {
                    //应收应付
                    $v['left_fee']=0;
                    if(isset($v['bizpro_class']))
                    {
                        $ids=explode(',',$v['bizpro_class']);
                        $v['bizpro_class_title'] = Db::name('bizpro_class')->where('id','in',$ids)->value('title');
                        $v['bizpro_class_arr']=$ids;
                    }
                    //状态
                    if(isset($v['audit_status']))
                    {
                        //通过
                        if(1== $v['audit_status'])
                        {
                            $v['audit_status_title']='待审核';
                            //已注册
                        }elseif(2== $v['audit_status'])
                        {
                            $v['audit_status_title']='合作中';
                        }elseif(4== $v['audit_status']){
                            $v['audit_status_title']='已关闭';
                        }
                    }
                    //地址
                    if(isset($v['province'])&&isset($v['city'])&&isset($v['area']))
                    {
                        $v['address_total']=$v['province'].$v['city'].$v['area'];
                    }
                    //供应商分类
                    /*
                    if(isset($v['bizpro_class'])&&!empty($v['bizpro_class']))
                    {
                        $cate_arr=explode(',',$v['bizpro_class']);
                        $res=[];
                        foreach ($cate_arr as $cate_k=>$cate_v)
                        {
                            $res[$cate_k]['p_class']=  $cate_v;
                            $res[$cate_k]['se_class_all']= Db::name('bizpro_class')->where(['pid'=>$cate_v])->field('id,title')->select();
                            $res[$cate_k]['se_class']=empty($v['bizpro_seclass'])?[]:explode(',',$v['bizpro_seclass']);
                        }
                        $v['bizpro_class_arr']=$res;
                    }
                    */
                    if(isset($v['id']))
                    {
                     $v['class']=Db::name('supplier_class')->where('supplier_id='.$v['id'])->select();
                     foreach ($v['class'] as &$vv)
                     {
                         $vv['seclass_title'] =Db::name('bizpro_class')->where('id='.$vv['seclass_id'])->value('title');
                     }
                    }

                    //应收应付
                    $v['pay_price']=PriceNumberFormat(Db::name('supplier_fee')->where('supplier_id='.$v['id'])->sum('pay_price'),2) ;
                   // dump($v['pay_price']);exit;
                }
            }
        }

        return DataReturn('获取成功',0,$data);
    }




    /**
     * 数据校验
     * @author   juzi
     * @blog     https://blog.csdn.net/juziaixiao
     * @version  1.0.0
     * @datetime  2020年7月23日12:06:23
     * @param    [array]          $params [输入参数]
     */
    public static function VaryData($params){
        // 公共数据校验请求参数
        $p = [
            [
                'checked_type'      => 'fun',
                'key_name'          => 'relation_phone',
                'checked_data'      => 'CheckMobile',
                'error_msg'         => '手机号码格式错误',
                'error_code' => 80002,
            ],

            [
                'checked_type' => 'empty',
                'key_name' => 'relation_name',
                'error_msg' => '联系人不能为空',
                'error_code' => 80001,
            ],
            [
                'checked_type' => 'empty',
                'key_name' => 'relation_phone',
                'error_msg' => '联系方式不能为空',
                'error_code' => 80003,
            ],
            [
                'checked_type' => 'empty',
                'key_name' => 'account_name',
                'error_msg' => '账户不能为空',
                'error_code' => 80004,
            ],
            [
                'checked_type' => 'empty',
                'key_name' => 'bank_account',
                'error_msg' => '账号不能为空',
                'error_code' => 80005,
            ],
            [
                'checked_type' => 'empty',
                'key_name' => 'open_bank',
                'error_msg' => '开户行不能为空',
                'error_code' => 80009,
            ],



        ];

        $ret=ParamsChecked($params, $p);

        if(true !== $ret)
        {
            //$error_arr[0]  $error_arr[1]
            $error_arr = explode(',', $ret);
            throw new BaseException(['code'=>403 ,'errorCode'=>$error_arr[1],'msg'=>$error_arr[0],'status'=>false,'debug'=>false ]);
        }
        #如果是终止合作 判断关联商品
        if($params['audit_status']==4)
        {
            SupplierService::VeryBeforeDel($params);
        }
        //名称重复判断
        $check_data = [
            'where' => [['supplier_name', '=', $params['supplier_name']],],
            'table' => 'supplier',
            'params' => $params,
            'msg' => '名称不能重复',
            'error_code' => 80006,
        ];
        CategoryService::CheckTitle($check_data);
        return true;
    }


    /**
     * 数据保存
     * @author   juzi
     * @blog     https://blog.csdn.net/juziaixiao
     * @version  1.0.0
     * @datetime 2020年7月10日11:08:21
     * @param    [array]          $params [输入参数]
     */
    public static  function SaveSup($params){


        Db::startTrans();
        $data=$params;
        //dump($data);exit;
        unset($data['bizpro_class']);
        unset($data['bizpro_seclass']);
        $data_se=[];
        // 添加/编辑
        if (empty($params['id']))
        {
            $industry_id = Db::name('supplier')->insertGetId($data);


            if (!$industry_id) {
                Db::rollback();
                throw new BaseException(['code'=>403 ,'errorCode'=>'80007','msg'=>'添加供应商失败','status'=>false,'debug'=>false]);
            }
        } else {
            $industry_id=intval($data['id']);
            //$data['update_time'] = TIMESTAMP;
            $re = Db::name('supplier')->where(['id' => intval($data['id'])])->update($data);
//            if (!$re) {
//                Db::rollback();
//                throw new BaseException(['code' => 403, 'errorCode' => '80008', 'msg' => '修改供应商失败', 'status' => false, 'debug' => false]);
//            }
        }
        foreach ($params['bizpro_class'] as $k=>$v)
        {
            $data_se[]=[
                'class_id'=>$v,
                'seclass_id'=>isset($params['bizpro_seclass'][$k])?$params['bizpro_seclass'][$k]:0,
                'supplier_id'=>$industry_id,
            ];
        }
        Db::name('supplier_class')->where('supplier_id='.$industry_id)->delete();
        Db::name('supplier_class')->insertAll($data_se);
        Db::commit();
        return true;
    }



    /**
     *数据处理
     * @author   juzi
     * @blog     https://blog.csdn.net/juziaixiao
     * @version  1.0.0
     * @datetime 2020年7月10日11:08:21
     * @param    [array]          $params [输入参数]
     */
    public static function HandleData($params){

        $data = $params;

        //删除多余字段
        $time_arr=join(',',$params['bizpro_class']);
        $data['bizpro_class']=$time_arr;
        $time_arr=join(',',$params['bizpro_seclass']);
        $data['bizpro_seclass']=$time_arr;
        return $data;
    }
    /**
     *数据验证
     * @author   juzi
     * @blog     https://blog.csdn.net/juziaixiao
     * @version  1.0.0
     * @datetime 2020年7月10日11:08:21
     * @param    [array]          $params [输入参数]
     */
    public static function VeryDataClient($params)
    {
        $p = [
            [
                'checked_type'      => 'empty',
                'key_name'          => 'relation_phone',
                'error_msg'         => '手机号码不能为空',
                'error_code' => 1001,
            ],
            [
                'checked_type'      => 'fun',
                'key_name'          => 'relation_phone',
                'checked_data'      => 'CheckMobile',
                'error_msg'         => '手机号码格式错误',
                'error_code' => 1002,
            ],
        ];

        $ret = ParamsChecked($params, $p);
        if($ret !== true)
        {
            $error_arr = explode(',', $ret);
            throw new BaseException(['code'=>403 ,'errorCode'=>$error_arr[1],'msg'=>$error_arr[0],'status'=>false,'debug'=>false ]);

        }
    }


    /**
     *删除前数据验证
     * @author   juzi
     * @blog     https://blog.csdn.net/juziaixiao
     * @version  1.0.0
     * @datetime 2020年7月10日11:08:21
     * @param    [array]          $params [输入参数]
     */
    public static function VeryBeforeDel($params)
    {
        $count=Db::name('bizpro')->where('status=1 and supplier_id='.$params['id'])->count();
        if($count>0)
        {
            throw new BaseException(['code'=>403 ,'errorCode'=>80010,'msg'=>'存在关联商品，无法删除','status'=>false,'debug'=>false ]);
        }
        return true;
    }

}